<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>交流区</title>
    <meta name="renderer" content="webkit">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
    <link rel="stylesheet" href="../lib/layui-v2.6.3/css/layui.css" media="all">
    <link rel="stylesheet" href="../font-awesome-4.7.0/css/font-awesome.min.css">
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
            font-family: "Microsoft YaHei", sans-serif;
        }

        body {
            background-color: #f2f6fc;
        }

        #message {
            max-width: 980px;
            margin: 20px auto;
            padding: 0 15px;
        }

        .title {
            text-align: center;
            margin-bottom: 20px;
            font-size: 28px;
            color: #1e9fff;
            padding: 10px 0;
        }

        .wrapper {
            background-color: #fff;
            border-radius: 8px;
            box-shadow: 0 2px 12px rgba(0,0,0,0.05);
            padding: 25px;
        }

        .title1, .content, .btn {
            margin-bottom: 20px;
        }

        .layui-input, .layui-textarea {
            border-radius: 4px;
        }

        .btn {
            display: flex;
            justify-content: flex-end;
        }

        .btn button {
            width: 120px;
            height: 40px;
            font-size: 16px;
        }

        .all {
            margin-top: 30px;
        }

        .msglist {
            list-style: none;
        }

        .list {
            background-color: #f8fafc;
            border-radius: 6px;
            padding: 20px;
            margin-bottom: 15px;
            position: relative;
            border-left: 4px solid #1e9fff;
            transition: all 0.3s;
            box-shadow: 0 1px 5px rgba(0,0,0,0.03);
        }

        .list:hover {
            background-color: #edf7ff;
            transform: translateY(-3px);
            box-shadow: 0 5px 15px rgba(0,0,0,0.05);
        }

        .list .title {
            text-align: left;
            font-size: 18px;
            font-weight: bold;
            color: #5f5f5f;
            margin: 0 0 10px 0;
            padding: 0;
            display: flex;
            align-items: center;
        }

        .list .title i {
            margin-right: 8px;
            color: #1e9fff;
        }

        .list .content {
            color: #555;
            line-height: 1.6;
            margin: 0 0 15px 0;
            padding: 0;
        }

        .list .date {
            color: #5f9de0;
            font-size: 13px;
            display: flex;
            align-items: center;
            margin-bottom: 10px;
        }

        .list .date i {
            margin-right: 5px;
        }

        .list .comment {
            background-color: #f0f7ff;
            border-radius: 4px;
            padding: 12px 15px;
            margin-bottom: 10px;
            color: #28b2b4;
            font-size: 14px;
            display: flex;
            align-items: center;
            border-left: 3px solid #5fb878;
        }

        .list .comment i {
            margin-right: 8px;
            font-size: 16px;
        }

        .replay {
            position: absolute;
            top: 20px;
            right: 20px;
            color: #ff6b6b;
            cursor: pointer;
            opacity: 0;
            transition: opacity 0.3s;
            font-size: 14px;
            display: flex;
            align-items: center;
        }

        .list:hover .replay {
            opacity: 1;
        }

        .replay i {
            margin-right: 5px;
        }

        .pagination {
            display: flex;
            justify-content: center;
            margin-top: 30px;
        }

        .empty-state {
            text-align: center;
            padding: 40px 0;
            color: #999;
        }

        .empty-state i {
            font-size: 60px;
            color: #e6e6e6;
            margin-bottom: 15px;
        }

        @media (max-width: 768px) {
            #message {
                padding: 0 10px;
            }

            .wrapper {
                padding: 20px 15px;
            }

            .replay {
                position: static;
                margin-top: 10px;
                opacity: 1;
            }
        }
    </style>
</head>
<body>
<div id="message">
    <div class="title">交流区</div>

    <div class="wrapper">
        <div class="title1">
            <input type="text" id="title" class="layui-input" placeholder="留言标题">
        </div>

        <div class="content">
            <textarea id="content" class="layui-textarea" placeholder="留言内容" rows="3"></textarea>
        </div>

        <div class="btn">
            <button class="layui-btn layui-btn-normal" id="submitBtn">
                <i class="fa fa-paper-plane"></i> 提交留言
            </button>
        </div>

        <div class="all">
            <ul class="msglist" id="msglist">
                <!-- 留言列表将通过JS动态生成 -->
                <div class="empty-state">
                    <i class="fa fa-comments-o"></i>
                    <div>正在加载留言数据...</div>
                </div>
            </ul>
        </div>

        <div class="pagination" id="pagination"></div>
    </div>
</div>

<script src="../lib/layui-v2.6.3/layui.js" charset="utf-8"></script>
<script>
    // 全局变量 - 保持与Vue组件相同的状态
    let flag = false;
    let current = 0;
    let pagination = {
        current: 1,
        total: 0,
        size: 4
    };

    layui.use(['layer', 'laypage'], function(){
        var layer = layui.layer;
        var laypage = layui.laypage;

        // 初始化页面
        getMsg();

        // 提交留言
        document.getElementById('submitBtn').addEventListener('click', function() {
            const title = document.getElementById('title').value;
            const content = document.getElementById('content').value;

            if (!title.trim() || !content.trim()) {
                layer.msg('留言标题或内容不能为空', {icon: 2});
                return;
            }

            // 获取当前时间
            const now = new Date();
            const time = now.toISOString();

            // 调用提交留言API
            fetch('/api/message', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({
                    title: title,
                    content: content,
                    time: time
                })
            })
                .then(response => response.json())
                .then(res => {
                    if (res.code === 200) {
                        layer.msg('留言发表成功', {icon: 1});
                        // 清空表单
                        document.getElementById('title').value = '';
                        document.getElementById('content').value = '';
                        // 刷新留言列表
                        getMsg();
                    } else {
                        layer.msg('留言失败: ' + (res.message || '未知错误'), {icon: 2});
                    }
                })
                .catch(error => {
                    console.error('提交留言失败:', error);
                    layer.msg('请求失败，请稍后重试', {icon: 2});
                });
        });

        // 获取留言列表
        function getMsg() {
            const url = `/api/messages/${pagination.current}/${pagination.size}`;

            fetch(url)
                .then(response => response.json())
                .then(res => {
                    if (res.code === 200) {
                        pagination = res.data;
                        renderMsgList();
                        renderPagination();
                    } else {
                        layer.msg('获取留言失败: ' + (res.message || '未知错误'), {icon: 2});
                    }
                })
                .catch(error => {
                    console.error('获取留言失败:', error);
                    layer.msg('请求失败，请稍后重试', {icon: 2});
                });
        }

        // 渲染留言列表
        function renderMsgList() {
            const container = document.getElementById('msglist');

            if (pagination.records && pagination.records.length > 0) {
                let html = '';

                pagination.records.forEach((data, index) => {
                    html += `
                <li class="list"
                    onmouseenter="enter(${index})"
                    onmouseleave="leave(${index})"
                    data-index="${index}">
                    <p class="title">
                        <i class="fa fa-commenting-o"></i>
                        ${data.title}
                    </p>
                    <p class="content">${data.content}</p>
                    <p class="date">
                        <i class="fa fa-clock-o"></i>
                        ${formatTime(data.time)}
                    </p>
                `;

                    if (data.replays && data.replays.length > 0) {
                        data.replays.forEach(replayData => {
                            html += `
                        <div>
                            <p class="comment">
                                <i class="fa fa-reply"></i>
                                ${replayData.replay}
                            </p>
                        </div>
                        `;
                        });
                    }

                    html += `
                    <span class="replay" onclick="reply(${data.id})">
                        <i class="fa fa-reply"></i> 回复
                    </span>
                </li>
                `;
                });

                container.innerHTML = html;
            } else {
                container.innerHTML = `
                <div class="empty-state">
                    <i class="fa fa-comments-o"></i>
                    <div>暂无留言，快来发表第一个留言吧！</div>
                </div>
            `;
            }
        }

        // 渲染分页
        function renderPagination() {
            laypage.render({
                elem: 'pagination',
                count: pagination.total,
                limit: pagination.size,
                curr: pagination.current,
                layout: ['count', 'prev', 'page', 'next', 'limit', 'skip'],
                limits: [4, 6, 8, 10],
                jump: function(obj, first) {
                    if (!first) {
                        pagination.current = obj.curr;
                        pagination.size = obj.limit;
                        getMsg();
                    }
                }
            });
        }

        // 格式化时间
        function formatTime(dateString) {
            const date = new Date(dateString);
            const year = date.getFullYear();
            const month = String(date.getMonth() + 1).padStart(2, '0');
            const day = String(date.getDate()).padStart(2, '0');
            const hours = String(date.getHours()).padStart(2, '0');
            const minutes = String(date.getMinutes()).padStart(2, '0');
            const seconds = String(date.getSeconds()).padStart(2, '0');

            return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
        }
    });

    // 回复留言
    function reply(messageId) {
        layui.use('layer', function(){
            var layer = layui.layer;

            layer.prompt({
                title: '回复留言',
                formType: 2,
                area: ['500px', '150px'],
                maxlength: 200
            }, function(value, index, elem) {
                if (!value.trim()) {
                    layer.msg('回复内容不能为空', {icon: 2});
                    return;
                }

                // 获取当前时间
                const now = new Date();
                const replayTime = now.toISOString();

                // 调用回复留言API
                fetch('/api/replay', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify({
                        replay: value,
                        replayTime: replayTime,
                        messageId: messageId
                    })
                })
                    .then(response => response.json())
                    .then(res => {
                        if (res.code === 200) {
                            layer.close(index);
                            layer.msg('回复成功', {icon: 1});
                            // 刷新留言列表
                            document.querySelectorAll('.list').forEach(item => {
                                if (parseInt(item.getAttribute('data-id')) === messageId) {
                                    const repliesContainer = item.querySelector('.replies');

                                    if (repliesContainer) {
                                        repliesContainer.innerHTML += `
                                <div class="reply-item">
                                    <div class="reply-content">
                                        <i class="fa fa-reply"></i> ${value}
                                    </div>
                                </div>
                                `;
                                    } else {
                                        item.innerHTML += `
                                <div class="replies">
                                    <div class="reply-item">
                                        <div class="reply-content">
                                            <i class="fa fa-reply"></i> ${value}
                                        </div>
                                    </div>
                                </div>
                                `;
                                    }
                                }
                            });
                        } else {
                            layer.msg('回复失败: ' + (res.message || '未知错误'), {icon: 2});
                        }
                    })
                    .catch(error => {
                        console.error('回复留言失败:', error);
                        layer.msg('请求失败，请稍后重试', {icon: 2});
                    });
            });
        });
    }

    // 鼠标进入事件
    function enter(index) {
        flag = true;
        current = index;

        // 显示当前项的回复按钮
        const items = document.querySelectorAll('.list');
        items.forEach((item, i) => {
            const replayBtn = item.querySelector('.replay');
            if (replayBtn) {
                replayBtn.style.opacity = i === index ? '1' : '0';
            }
        });
    }

    // 鼠标离开事件
    function leave(index) {
        flag = false;
        current = index;

        // 隐藏所有回复按钮
        document.querySelectorAll('.replay').forEach(btn => {
            btn.style.opacity = '0';
        });
    }
</script>
</body>
</html>